//
//  ListTableViewController.m
//  出行助手
//
//  Created by lanou3g on 16/8/12.
//  Copyright © 2016年 110. All rights reserved.
//

#import "ListTableViewController.h"
#import "MapViewController.h"
#import "ListTableViewCell.h"
#import "Size.h"
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>

@interface ListTableViewController ()<BMKPoiSearchDelegate, BMKLocationServiceDelegate>

@property(strong, nonatomic)NSMutableArray *dataArray;//数据源数组
@property(strong, nonatomic)BMKPoiSearch *poiSearch;//POI检索对象
@property(strong, nonatomic)BMKUserLocation *userLocation;//用户当前位置
@property(strong, nonatomic)BMKLocationService *locationService;//定位对象

@end

@implementation ListTableViewController

-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}
//懒加载初始化检索对象
-(BMKPoiSearch *)poiSearch
{
    if (_poiSearch == nil) {
        _poiSearch = [[BMKPoiSearch alloc]init];
    }
    _poiSearch.delegate = self;
    return _poiSearch;
}
//懒加载初始化位置服务对象
-(BMKLocationService *)locationService
{
    if (_locationService == nil) {
        _locationService = [[BMKLocationService alloc]init];
    }
    _locationService.delegate = self;
    return _locationService;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.poiString;
    
    //启动定位服务
    [self.locationService startUserLocationService];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ListTableViewCell" bundle:nil] forCellReuseIdentifier:@"listCell"];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.userLocation != nil) {
        NSLog(@"已经获取当前位置, %@", self.userLocation);
        //开始检索
        BMKNearbySearchOption *searchOption = [[BMKNearbySearchOption alloc]init];
        searchOption.pageIndex = 0;//当前页码
        searchOption.pageCapacity = 50;//信息条数
        searchOption.location = self.userLocation.location.coordinate;//根据当前位置经纬度进行搜索
        searchOption.keyword = self.poiString;
        BOOL flag = [self.poiSearch poiSearchNearBy:searchOption];
        if (flag) {
            NSLog(@"附近检索成功");
        }else{
            NSLog(@"附近检索失败");
        }
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.poiSearch.delegate = nil;
//    self.mapView.delegate = nil;
    self.locationService.delegate = nil;
}

#pragma mark BMKPoiSearchDelegate代理方法
/**
 *返回POI搜索结果
 *@param searcher 搜索对象
 *@param poiResult 搜索结果列表
 *@param errorCode 错误号，@see BMKSearchErrorCode
 */
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResult errorCode:(BMKSearchErrorCode)errorCode
{
    //检测到结果时执行
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        [poiResult.poiInfoList enumerateObjectsUsingBlock:^(BMKPoiInfo *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (![self.dataArray containsObject:obj]) {
                [self.dataArray addObject:obj];
            }
        }];
        [self.tableView reloadData];
    }
    else if (errorCode == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        NSLog(@"起始点有歧义");
    } else {
        NSLog(@"抱歉，周边检索未找到结果,转成城市检索, %d",errorCode);
        BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];
        citySearchOption.pageIndex = 0;
        citySearchOption.pageCapacity = 50;
        citySearchOption.city = @"北京";
        citySearchOption.keyword = self.poiString;
        BOOL flag = [self.poiSearch poiSearchInCity:citySearchOption];
        if (flag) {
            NSLog(@"城市内检索成功");
        }else{
            NSLog(@"城市内检索失败");
        }
    }

}

#pragma mark BMKLocationServiceDelegate代理方法
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    self.userLocation = userLocation;
    if (self.userLocation) {
        //停止定位服务
        NSLog(@"定位成功");
        NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
        [self.tableView reloadData];
        [self.locationService stopUserLocationService];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell" forIndexPath:indexPath];
    BMKPoiInfo *poiInfo = self.dataArray[indexPath.row];
    cell.nameLabel.text = poiInfo.name;
    cell.addressLabel.text = poiInfo.address;
    if (poiInfo.phone) {
        cell.phoneLabel.text = poiInfo.phone;
    }
    [cell.navButton addTarget:self action:@selector(navAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BMKPoiInfo *poiInfo = self.dataArray[indexPath.row];
    CGFloat addressHeight = [self textHeight:poiInfo.address];
    return 140 + addressHeight - 30;
}

-(void)navAction:(UIButton *)sender
{
    
}

//计算文本高度
-(CGFloat)textHeight:(NSString *)string
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(addressWidth, 1000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
    return rect.size.height;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
